package com.hanxiaozhang.stackandqueue;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用数组创建循环队列〉
 *
 * @author hanxinghua
 * @create 2021/9/6
 * @since 1.0.0
 */
public class QueueWhileArray {

    public static void main(String[] args) {
        QueueWhileArray myQueueWhileArray = new QueueWhileArray(4);
        myQueueWhileArray.push(1);
        myQueueWhileArray.push(2);
        myQueueWhileArray.push(3);
        myQueueWhileArray.push(4);
        myQueueWhileArray.printStackHeadWhile();
        System.out.println("-------");
        System.out.println(myQueueWhileArray.pop());
        System.out.println(myQueueWhileArray.pop());
        System.out.println(myQueueWhileArray.pop());
        System.out.println(myQueueWhileArray.pop());
        // System.out.println(myQueueWhileArray.pop());
    }

    /**
     * 数组
     */
    private int[] array;

    /**
     * 下一个推送索引
     */
    private int pushIndex;

    /**
     * 下一个弹出索引
     */
    private int pollIndex;

    /**
     * 大小
     */
    private int size;

    /**
     * 容量
     */
    private final int capacity;

    public QueueWhileArray(int capacity) {
        array = new int[capacity];
        pushIndex = 0;
        pollIndex = 0;
        size = 0;
        this.capacity = capacity;
    }


    public void push(int value) {
        if (size == capacity) {
            throw new RuntimeException("QueueWhileArray is full, not push");
        }
        size++;
        array[pushIndex] = value;
        pushIndex = nextIndex(pushIndex);
    }

    public int pop() {
        if (size == 0) {
            throw new RuntimeException("QueueWhileArray is null, not pop");
        }
        size--;
        int ans = array[pollIndex];
        pollIndex = nextIndex(pollIndex);
        return ans;
    }

    public boolean isEmpty() {
        return size == 0;
    }


    /**
     * 栈顶打印原始
     */
    public void printStackHeadWhile() {
        System.out.println("-------");
        int printIndex = superIndex(pushIndex);
        for (int s = 0; s < size; s++) {
            System.out.println(array[printIndex]);
            printIndex = superIndex(printIndex);
        }
    }


    /**
     * 获取上标
     *
     * @param i
     * @return
     */
    private int superIndex(int i) {
        return i == 0 ? capacity - 1 : i - 1;
    }

    /**
     * 获取下标
     *
     * @param i
     * @return
     */
    private int nextIndex(int i) {
        return i < capacity - 1 ? i + 1 : 0;
    }


}
